package com.starp.add.controller;
//import com.example.demo.entity.Student;
//import com.example.demo.repository.StudentRepository;
import com.starp.add.entity.ReturnT;
import com.starp.add.entity.Student;
import com.starp.add.repository.StudentRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @description student
 * @author mqp
 * @date 2021-08-20
 */
@Api(tags = "student")
@RestController
@Slf4j
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentRepository studentRepository;
    /**
     * 新增或编辑
     */
    @ApiOperation(value = "")
    @PostMapping("/saveBatch")
    public Object saveBatch(@RequestBody  Student student){
        long start=System.currentTimeMillis();
        return studentRepository.save(student);
    }



    /**
    * 新增或编辑
    */
    @ApiOperation(value = "")
    @PostMapping("/save")
    public Object save(@RequestBody  Student student){
        return studentRepository.save(student);
    }

    /**
    * 删除
    */
    @ApiOperation(value = "")
    @PostMapping("/delete")
    public Object delete(int id){
        Optional<Student> student=studentRepository.findById(id);
        if(student.isPresent()){
            studentRepository.deleteById(id);
            return ReturnT.success("删除成功");
        }else{
            return ReturnT.error("没有找到该对象");
        }
    }

    /**
    * 查询
    */
    @PostMapping("/find")
    public Object find(int id){
        Optional<Student> student=studentRepository.findById(id);
        if(student.isPresent()){
            return ReturnT.success(student.get());
        }else{
            return ReturnT.error("没有找到该对象");
        }
    }

    /**
    * 分页查询
    */
    @PostMapping("/list")
    public Object list(@RequestBody Student student,
                        @RequestParam(required = false, defaultValue = "0") int pageNumber,
                        @RequestParam(required = false, defaultValue = "10") int pageSize) {

            //创建匹配器，需要查询条件请修改此处代码
            ExampleMatcher matcher = ExampleMatcher.matchingAll();

            //创建实例
            Example<Student> example = Example.of(student, matcher);
            //分页构造
            Pageable pageable = PageRequest.of(pageNumber,pageSize);

            return studentRepository.findAll(example, pageable);
    }

}